package com.darker.demo;

/**
 * @auther lj
 * @date 2018/7/31 11:37
 * @email lmwtuedu@163.com
 */
public class WaitNotify {
    static Object lock = new Object();

    static boolean flag =true;

    public static void main(String[] args) throws InterruptedException {
        Thread wait = new Thread(new Wait(), "wait");
        Thread notify = new Thread(new Notify(), "notify");

        wait.start();

        Thread.sleep(10000);

        notify.start();
    }

    static class Wait implements Runnable{
        @Override
        public void run() {

            // lock
            synchronized (lock){

                try {
                    while (flag){
                        System.out.println( Thread.currentThread() + "flag is true , wait...");
                        System.out.println(" time is :" + System.currentTimeMillis());

                        lock.wait(); // 会释放锁
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println( Thread.currentThread() + "flag is false, running...");
                System.out.println(" time is :" + System.currentTimeMillis());
            }

        }
    }

    static class Notify implements Runnable{
        @Override
        public void run() {
            synchronized (lock){
                // 获取lock的锁，然后进行通知，通知的时候不会释放锁
                // 直到当前线程释放了lock后，WaitThread才能从wait方法中返回

                System.out.println(Thread.currentThread() + " hold lock , notify, time is : " + System.currentTimeMillis());

                lock.notifyAll();

                flag = false;   // 状态改变
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            synchronized (lock){
                System.out.println( Thread.currentThread() + "hold lock again, time is : " + System.currentTimeMillis());
            }
        }
    }
}
